package com.tian.photopicker.ui;


import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.tian.photopicker.R;
import com.tian.photopicker.adapter.PickerGridAdapter;
import com.tian.photopicker.adapter.PopupDirectoryAdapter;
import com.tian.photopicker.bean.BundleBean;
import com.tian.photopicker.bean.Photo;
import com.tian.photopicker.bean.PhotoDirectory;
import com.tian.photopicker.data.MediaStoreHelper;
import com.tian.photopicker.util.AndroidLifecycleUtils;
import com.tian.photopicker.util.GetImagePath;
import com.tian.photopicker.util.PermissionsUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static com.tian.photopicker.PhotoPicker.IS_SHOW_CAMERA;
import static com.tian.photopicker.PhotoPicker.KEY_SELECTED_PHOTOS;
import static com.tian.photopicker.PhotoPicker.RECYCLER_VIEW_COLUMNS;
import static com.tian.photopicker.PhotoPicker.SELECT_PHOTO_COUNT;
import static com.tian.photopicker.ui.PhotoPickerActivity.DEFAULT_COLUMNS;
import static com.tian.photopicker.ui.PhotoPickerActivity.DEFAULT_MAX_SELECT_COUNT;

/**
 * 选择
 * @author tian
 */
public class PhotoPickerFragment extends Fragment implements PhotoPreviewFragment.OnUpdateSelectInfo{
    private int columns;
    private int maxCount;
    private PickerGridAdapter gridAdapter;
    private RequestManager glideRequest;
    private List<PhotoDirectory>  directoryList;
    private List<Photo> photoData;
    private ImageView ivBack;
    private TextView title;
    private TextView btnFinish;
    private RelativeLayout rlBottom;
    private TextView tvPhotoDir;
    private TextView tvPreView;
    /**
     * 用于显示文件夹列表
     */
    private ListPopupWindow listPopupWindow;

    private PopupDirectoryAdapter popopAdapter;
    private int SCROLL_THRESHOLD = 30;
    private int selectCount;
    //缓存Fragment view
    private View rootView;
    private static BundleBean bundleBean;
    private File cameraTargetFile;
    private File outPutFile;

    public static PhotoPickerFragment newInstance(BundleBean bean) {
        Bundle args = new Bundle();
        args.putBoolean(IS_SHOW_CAMERA, bean.isShowCamera());
        args.putInt(RECYCLER_VIEW_COLUMNS, bean.getColumn());
        args.putInt(SELECT_PHOTO_COUNT, bean.getSelectCount());
        bundleBean = bean;
        PhotoPickerFragment fragment = new PhotoPickerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        glideRequest = Glide.with(this);
        directoryList = new ArrayList<>();
        photoData = new ArrayList<>();
        columns = getArguments().getInt(RECYCLER_VIEW_COLUMNS,DEFAULT_COLUMNS);
        boolean showCamera = getArguments().getBoolean(IS_SHOW_CAMERA,true);
        maxCount = getArguments().getInt(SELECT_PHOTO_COUNT,DEFAULT_MAX_SELECT_COUNT);
        gridAdapter = new PickerGridAdapter(getActivity(),glideRequest, photoData);
        gridAdapter.setShowCamera(showCamera);
        popopAdapter = new PopupDirectoryAdapter(glideRequest,directoryList);
        Bundle bundleMedia = new Bundle();
        MediaStoreHelper.getPhotoDirs(getActivity(), bundleMedia,
                new MediaStoreHelper.PhotosResultCallback() {
                    @Override public void onResultCallback(List<PhotoDirectory> dirs) {
                        directoryList.clear();
                        directoryList.addAll(dirs);
                        if (directoryList.size() > 0) {
                            photoData = directoryList.get(0).getPhotos();
                        }

                        gridAdapter.setNewData(photoData);
                        popopAdapter.notifyDataSetChanged();
                        adjustHeight();
                    }
                });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_photo_picker, container, false);
            initComponent(rootView);
        } else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null){
                parent.removeView(rootView);
            }
        }
        return rootView;
    }


    /**
     * 初始化控件
     * @param mView
     */
    private void initComponent(View mView) {
        ivBack = (ImageView) mView.findViewById(R.id.iv_pick_back);
        title = (TextView) mView.findViewById(R.id.picker_title);
        btnFinish = (TextView) mView.findViewById(R.id.btn_finish);
        rlBottom = (RelativeLayout) mView.findViewById(R.id.rl_bottom);
        tvPhotoDir = (TextView) mView.findViewById(R.id.tv_chose_dir);
        tvPreView = (TextView) mView.findViewById(R.id.tv_preview);
        RecyclerView recyclerView = (RecyclerView) mView.findViewById(R.id.picker_rv);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),columns));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(gridAdapter);
        listPopupWindow = new ListPopupWindow(getActivity());
        listPopupWindow.setWidth(ListPopupWindow.MATCH_PARENT);
        listPopupWindow.setAnchorView(rlBottom);
        listPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        listPopupWindow.setAdapter(popopAdapter);
        listPopupWindow.setModal(true);
        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                listPopupWindow.dismiss();
                PhotoDirectory directory = directoryList.get(position);
                tvPhotoDir.setText(directory.getName());
                title.setText(directory.getName());
                photoData = directoryList.get(position).getPhotos();
                gridAdapter.setCurrentDirectoryIndex(position);
                gridAdapter.setNewData(photoData);
            }
        });
        /**
         * 滑动监听
         */
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (Math.abs(dy) > SCROLL_THRESHOLD) {
                    glideRequest.pauseRequests();
                } else {
                    resumeRequestsIfNotDestroyed();
                }
            }
            @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    resumeRequestsIfNotDestroyed();
                }
            }
        });
        gridAdapter.setOnItemCheckListener(new PickerGridAdapter.OnItemCheckListener() {
            @Override
            public boolean onItemCheck(int position, Photo path, int selectedItemCount) {
                btnFinish.setEnabled(selectedItemCount > 0);
                tvPreView.setEnabled(selectedItemCount > 0);
                if (selectedItemCount == 0) {
                    btnFinish.setText("完成");
                    tvPreView.setText("预览");
                    return true;
                }
                if (selectedItemCount > maxCount) {
                    Toast.makeText(getActivity(), "您最多只能选择"+maxCount
                            +"张图片", Toast.LENGTH_SHORT).show();
                    return false;
                }
                selectCount = selectedItemCount;
                btnFinish.setText("完成(" +selectedItemCount +"/" +maxCount +")");
                tvPreView.setText("预览(" +selectedItemCount +")");
                return true;
            }
        });
        gridAdapter.setOnPhotoClickListener(new PickerGridAdapter.OnPhotoClickListener() {
            @Override
            public void onClick(View v, int position, boolean showCamera) {
                int index = showCamera ? position - 1 : position;
                PhotoPreviewFragment photoPreviewFragment =
                        PhotoPreviewFragment.newInstance(gridAdapter.getCurrentPhotoPaths(), index,selectCount,maxCount);
                photoPreviewFragment.setmOnUpdateSelectInfo(PhotoPickerFragment.this);
                ((PhotoPickerActivity)getActivity())
                        .addPreviewImageFragment(photoPreviewFragment);
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //  点击退出
                getActivity().finish();
            }
        });
        /**
         * 点击预览
         */
        tvPreView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> list = gridAdapter.getSelectedPhotoPaths();
                PhotoPreviewFragment photoPreviewFragment =
                        PhotoPreviewFragment.newInstance(list, 0,selectCount,selectCount);
                photoPreviewFragment.setmOnUpdateSelectInfo(PhotoPickerFragment.this);
                ((PhotoPickerActivity)getActivity())
                        .addPreviewImageFragment(photoPreviewFragment);
            }
        });
        /**
         * 选择文件夹
         */
        tvPhotoDir.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listPopupWindow.isShowing()) {
                    listPopupWindow.dismiss();
                } else if (!getActivity().isFinishing()) {
                    adjustHeight();
                    listPopupWindow.show();
                }
            }
        });
        /**
         * 点击完成
         */
        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                ArrayList<String> selectedPhotos = gridAdapter.getSelectedPhotoPaths();
                if (bundleBean.isCrop()) {
                    File file =new File(selectedPhotos.get(0));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri inputUri = FileProvider.getUriForFile(getActivity(),  getActivity().getApplicationInfo().packageName + ".provider", file);
                        startCrop(inputUri);
                    } else {
                        Uri inputUri = Uri.fromFile(file);
                        startCrop(inputUri);
                    }
                } else {
                    intent.putStringArrayListExtra(KEY_SELECTED_PHOTOS, selectedPhotos);
                    getActivity().setResult(RESULT_OK, intent);
                    getActivity().finish();
                }

            }
        });
        gridAdapter.setOnCameraClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击摄像机
                if (!PermissionsUtils.checkCameraPermission(PhotoPickerFragment.this)) {
                    return;
                }
                if (!PermissionsUtils.checkWriteStoragePermission(PhotoPickerFragment.this)) {
                    return;
                }
                openCamera();
            }
        });
    }

    /**
     * 打开摄像机
     */
    private void openCamera() {
        try {
            cameraTargetFile =  createTempImageFile();
            //跳转到拍照界面.
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //兼容
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            {
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                //通过FileProvider创建一个content类型的Uri
                Uri contentUri = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationInfo().packageName + ".provider", cameraTargetFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
            } else
            {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraTargetFile));
            }
            startActivityForResult(intent, 1001);


        } catch (Exception e) {
            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    public void finish(String imgPath) {
        Intent intent = new Intent();
        ArrayList<String> selectedPhotos = new ArrayList<>();
        selectedPhotos.add(imgPath);
        intent.putStringArrayListExtra(KEY_SELECTED_PHOTOS, selectedPhotos);
        getActivity().setResult(RESULT_OK, intent);
        getActivity().finish();
    }
    /**
     * 创建临时文件
     * @return
     */
    private File createTempImageFile() {
        File imagePath = new File(Environment.getExternalStorageDirectory(), "images");
        if (!imagePath.exists()) {
            imagePath.mkdirs();
        }
        File newFile = new File(imagePath, "photo_img"+".jpg");
        return newFile;
    }

    /**
     * 权限处理
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            switch (requestCode) {
                case PermissionsUtils.REQUEST_CAMERA:
                case PermissionsUtils.REQUEST_EXTERNAL_WRITE:
                    if (PermissionsUtils.checkWriteStoragePermission(this) &&
                            PermissionsUtils.checkCameraPermission(this)) {
                        openCamera();
                    } else {
                        Toast.makeText(getActivity(), "请在应用设置中打开照相机权限", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case PermissionsUtils.REQUEST_EXTERNAL_READ:
                    if (!PermissionsUtils.checkReadStoragePermission(getActivity())) {
                        Toast.makeText(getActivity(), "请在应用设置中打开存储权限", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }
    }
    public PickerGridAdapter getPickerGridAdapter() {
        return gridAdapter;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1001) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Uri inputUri = FileProvider.getUriForFile(getActivity(),  getActivity().getApplicationInfo().packageName + ".provider", cameraTargetFile);//通过FileProvider创建一个content类型的Uri
                    if (bundleBean.isCrop()) {
                        startCrop(inputUri);
                    } else {
                        finish(cameraTargetFile.getAbsolutePath());
                    }
                } else {
                    Uri inputUri = Uri.fromFile(cameraTargetFile);
                    if (bundleBean.isCrop()) {
                        startCrop(inputUri);
                    } else  {
                        finish(cameraTargetFile.getAbsolutePath());
                    }
                }
            } else if (requestCode == 1002){
                finish(outPutFile.getAbsolutePath());
            }
        }
    }

    /**
     * 裁剪
     * @param inputUri
     */
    private void startCrop(Uri inputUri) {
        if (inputUri == null) {
            return;
        }
        outPutFile=createTempImageFile();
        Intent intent = new Intent("com.android.camera.action.CROP");
        //sdk>=24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri outPutUri = Uri.fromFile(outPutFile);
            intent.setDataAndType(inputUri, "image/*");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutUri);
            intent.putExtra("noFaceDetection", false);//去除默认的人脸识别，否则和剪裁匡重叠
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        } else {
            Uri outPutUri = Uri.fromFile(outPutFile);
            if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                String url = GetImagePath.getPath(getActivity(), inputUri);//这个方法是处理4.4以上图片返回的Uri对象不同的处理方法
                intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
            } else {
                intent.setDataAndType(inputUri, "image/*");
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutUri);
        }
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);//1.1
        intent.putExtra("aspectY", 1);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());// 图片格式
        startActivityForResult(intent, 1002);//这里就将裁剪后的图片的Uri返回了
    }

    /**
     * 恢复Glide请求
     */
    private void resumeRequestsIfNotDestroyed() {
        if (!AndroidLifecycleUtils.canLoadImage(this)) {
            return;
        }

        glideRequest.resumeRequests();
    }
    /**
     * 弹窗高度
     */
    public void adjustHeight() {
        if (popopAdapter == null) {
            return;
        }
        int count = popopAdapter.getCount();
        count = count < 6 ? count : 6;
        if (listPopupWindow != null) {
            listPopupWindow.setHeight(count * 150);
        }
    }

    @Override
    public void updateStatus(int selectCount) {
        gridAdapter.notifyDataSetChanged();
        btnFinish.setEnabled(selectCount > 0);
        tvPreView.setEnabled(selectCount > 0);
        this.selectCount = selectCount;
        if (selectCount == 0) {
            btnFinish.setText("完成");
            tvPreView.setText("预览");
            return;
        }
        btnFinish.setText("完成(" +selectCount +"/" +maxCount +")");
        tvPreView.setText("预览(" +selectCount +")");
    }
}
